package com.buer.storage.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.FastDateFormat;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 类名
 *
 * @author wangs
 * @date 2020-07-21 14:30
 */
public class DateUtil {


    public final static String date_time_format_ymd_hms = "yyyy-MM-dd HH:mm:ss";

    public final static String date_time_format_ymd_hms_chinese = "yyyy年MM月dd日 HH:mm:ss";

    public final static String date_format_ymd = "yyyy-MM-dd";

    public final static String date_format_ymd_chinese = "yyyy年MM月dd日";

    public final static String date_format_ymd_hm = "yyyy-MM-dd HH:mm";

    public final static String date_format_ymd_hm_chinese = "yyyy年MM月dd日HH时mm分";

    /**
     * 获得当前日期的字符串（yyyy-MM-dd HH:mm:ss）
     *
     * @return
     */
    public static String getCurrDayTime() {
        return longToString(System.currentTimeMillis(), date_time_format_ymd_hms);
    }

    /**
     * 获得当前日期的字符串（yyyy-MM-dd）
     *
     * @return
     */
    public static String getCurrDate() {
        return longToString(System.currentTimeMillis(), date_format_ymd);
    }

    /**
     *解析字符串
     * @param dateStr
     * @return 返回日期对象
     */
    public static Date parseDate(String dateStr, String pattern) {
        try {
            return DateUtils.parseDate(dateStr,new String[]{pattern});
        } catch (ParseException e) {
            return null;
        }
    }

    public static Date getFormatDate(Object obj_creationTime, int a) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 24小时制
        String str_creationTime = obj_creationTime.toString();
        String creationTime = str_creationTime.substring(0, 4) + "-" + str_creationTime.substring(4, 6) + "-"
                + str_creationTime.substring(6, 8) + " " + str_creationTime.substring(9, 11) + ":"
                + str_creationTime.substring(11, 13) + ":" + str_creationTime.substring(13, 15);
        Date date = sdf.parse(creationTime);
        Calendar cal = Calendar.getInstance();
        // 调整为北京时间增加8小时
        cal.setTime(date);
        cal.add(Calendar.HOUR, a);// 24小时制
        date = cal.getTime();
        return date;
    }

    /**
     * timeStamp转换字符串
     *
     * @param timestamp
     * @param formatStr
     * @return
     */
    public static String timestampToString(Timestamp timestamp, String formatStr) {
        if (formatStr == null) {
            formatStr = date_time_format_ymd_hms;
        }
        DateFormat format = new SimpleDateFormat(formatStr);
        String s = format.format(timestamp);
        return s;
    }

    /**
     * timeStamp转换字符串
     *
     * @param timestamp
     * @param formatStr
     * @return
     */
    public static String dateToString(Date timestamp, String formatStr) {
        if (formatStr == null) {
            formatStr = date_time_format_ymd_hms;
        }
        DateFormat format = new SimpleDateFormat(formatStr);
        String s = format.format(timestamp);
        return s;
    }

    /**
     * long转换成字符串
     *
     * @param timestamp
     * @param formatStr
     * @return
     */
    public static String longToString(long timestamp, String formatStr) {
        if (formatStr == null)
            formatStr = date_time_format_ymd_hms;
        DateFormat format = new SimpleDateFormat(formatStr);
        String s = format.format(timestamp);
        return s;
    }

    /**
     * 字符串转换成long
     *
     * @param dateStr
     * @param formatStr
     * @return
     */
    public static long StringToLong(String dateStr, String formatStr) {
        DateFormat format = new SimpleDateFormat(formatStr);
        try {
            Date date = format.parse(dateStr);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0l;
    }

    /**
     * @throws
     * @Title:getDayOfYear
     * @Description:获取该时间是一年的第几天
     * @return:int
     */
    public static int getDayOfYear(long dateLong) {
        Calendar calender = Calendar.getInstance();
        calender.setTimeInMillis(dateLong);
        return calender.get(Calendar.DAY_OF_YEAR);
    }

    /**
     * @throws
     * @Title:getYearByDate
     * @Description:获取该时间的年
     * @return:int
     */
    public static int getYearByDate(Timestamp createDate) {
        Calendar calender = Calendar.getInstance();
        calender.setTimeInMillis(createDate.getTime());
        return calender.get(Calendar.YEAR);
    }

    private static String delimiter = "-";// 分隔字符

    //格式化年月日
    public static Date dateFormat(Date date) {
        if (date != null) {
            String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
            Date date2 = null;
            try {
                date2 = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return date2;
        } else {
            return null;
        }
    }

    /**
     * @throws
     * @Title:differentDays
     * @Description:时间计算差值
     * @return:int
     */
    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2)   //同一年
        {
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)    //闰年
                {
                    timeDistance += 366;
                } else    //不是闰年
                {
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2 - day1);
        } else    //不同年
        {
            System.out.println("判断day2 - day1 : " + (day2 - day1));
            return day2 - day1;
        }
    }

    /**
     * 获取本周的周一 和 周日
     *
     * @param date
     * @return
     */
    public static List<Date> getStartAndEndOfWeek(Date date) {
        List<Date> result = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        result.add(calendar.getTime());
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        result.add(calendar.getTime());
        return result;
    }

    public static List<Date> getStartAndEndOfMonth(Date date) {
        List<Date> result = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        result.add(calendar.getTime());
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        result.add(calendar.getTime());
        return result;
    }

    /**
     * 将日期时间从一种格式转换为另一种格式
     * @param srcDateTime 源串
     * @param srcPattern	源串格式
     * @param destPattern 目标串格式
     * @return String 目标串
     */
    public static String transDateTime(String srcDateTime,	String srcPattern,	String destPattern) {
        srcDateTime = StringUtils.defaultString(srcDateTime).trim();
        try {
            srcDateTime = FastDateFormat.getInstance(destPattern).format(parseDate(srcDateTime, srcPattern));
        } catch (Exception exp) {
        }
        return srcDateTime;
    }

    /**
     * 将字符串格式日期转化为 yyyy-MM-dd 格式字符串
     * @param srcDate
     * @return String
     */
    public static String transDate(String srcDate) {
        srcDate = StringUtils.defaultString(srcDate).trim();
        if (srcDate.length() == 14)
            return transDateTime(srcDate,"yyyyMMddHHmmss","yyyy-MM-dd");
        if (srcDate.length() == 12)
            return transDateTime(srcDate,"yyyyMMddHHmm","yyyy-MM-dd");
        if (srcDate.length() == 8)
            return transDateTime(srcDate,"yyyyMMdd","yyyy-MM-dd");
        return srcDate;
    }

    /**
     * 将yyyy/mm/dd字符串格式日期转化为 yyyy-MM-dd 格式字符串
     * @param srcDate
     * @return String
     */
    public static String transDate4Str(String srcDate) {
        srcDate = StringUtils.defaultString(srcDate).trim();
        String regex="^\\d{4}-\\d{2}-\\d{2}$";
        Pattern p =Pattern.compile(regex);
        Matcher matcher =p.matcher(srcDate);
        if(!matcher.find()){
            String[] arr = srcDate.split("/");
            if(arr.length==3){
                String y = arr[0];
                String m = arr[1];
                String d = arr[2];
                if(m.length()==1){
                    m = "0"+m;
                }
                if(d.length()==1){
                    d = "0"+d;
                }
                return y + "-" + m + "-" + d;
            }
        }
        return srcDate;
    }
    /**
     * 获得当月第一天
     */

    public static String getFirstDayOfMonth(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal_1 = Calendar.getInstance();//获取当前日期
        cal_1.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
        String firstDay = format.format(cal_1.getTime());
        return firstDay;
    }

    /**
     * 获取指定年月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static String getLastDayOfMonth(int year, int month)
    {
        Calendar cal = Calendar.getInstance();
        // 设置年份
        cal.set(Calendar.YEAR, year);
        // 设置月份
        cal.set(Calendar.MONTH, month - 1);
        // 获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        // 设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /**
     * 返回两个日期的天数
     * @param small
     * @param big
     * @return
     * @throws ParseException
     */
    public static int daysBetween(Date small, Date big) throws ParseException
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        small = sdf.parse(sdf.format(small));
        big = sdf.parse(sdf.format(big));
        Calendar cal = Calendar.getInstance();
        cal.setTime(small);
        long time1 = cal.getTimeInMillis();
        cal.setTime(big);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }



    public static void main(String[] args) {
        List<Date> result = getStartAndEndOfMonth(new Date());
        System.out.println(result);

    }
}
